<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/6/11
 * Time: 12:39
 */
class SignAction extends Action
{
    /**新建或修改签到奖励
     * @param string $id
     * @param string $name
     * @param string $tagId
     * @param string $startTime
     * @param string $endTime
     * @param string $pointSchemeId
     * @param string $picUrl
     * @param string $bgPicUrl
     * @param string $signPicUrl
     * @param string $afterSignPicUrl
     * @param string $rulePicUrl
     * @param string $description
     */
    public function operateSignReward(
        $id = '',
        $name = '',
        $tagId = '',
        $startTime = '',
        $endTime = '',
        $pointSchemeId = '',
        $picUrl = '',
        $bgPicUrl = '',
        $signPicUrl = '',
        $afterSignPicUrl = '',
        $rulePicUrl = '',
        $description = ''
    )
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signInModel = M('sign_in_reward');
        $signTagModel = M('sign_reward_tag');
        Session::switchCustomer($customerId);

        if ($pointSchemeId > 0 && $id) {
            $res = $signInModel->where("id = $id")->setField('pointSchemeId', $pointSchemeId);
            if (is_numeric($res)) {
                Output::instance()->object([
                    'code' => 0,
                    'msg' => 'ok'
                ]);
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '失败'
                ]);
            }
            return;
        }
        if (!empty($tagId)) $arrTagId = explode(',', $tagId);
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'updateTime' => date('Y-m-d H:i:s', time()),
            'picUrl' => $picUrl,
            'bgPicUrl' => $bgPicUrl,
            'signPicUrl' => $signPicUrl,
            'afterSignPicUrl' => $afterSignPicUrl,
            'rulePicUrl' => $rulePicUrl,
            'description' => $description
        );

        if (empty($id)) {
            $data['createTime'] = date('Y-m-d H:i:s', time());
            $res = $signInModel->add($data);
            if (!empty($arrTagId)) {
                foreach ($arrTagId as $value) {
                    $tagData = [
                        'signRewardId' => $res,
                        'tagId' => $value
                    ];
                    $signTagModel->add($tagData); //添加标签与方案对应记录
                }
            }
            $signId = $res; //前端需要新添加的方案ID
        } else {
            unset($data['createTime']);
            $res = $signInModel->where("id = $id")->save($data);
            $signTagModel->where("signRewardId = $id")->delete();
            if (!empty($arrTagId)) {
                foreach ($arrTagId as $value) {
                    $tagData = [
                        'signRewardId' => $id,
                        'tagId' => $value
                    ];
                    $signTagModel->add($tagData); //添加标签与方案对应记录
                }
            }
            $signId = $id;
        }

        if (is_numeric($res)) {
            $sql = $signTagModel->getLastSql();
            if ($id) {
                R('Log/add',array('signReward','','签到奖励',op_update,$sql,'修改签到奖励：' . $name));
            } else {
                R('Log/add',array('signReward','','签到奖励',op_add,$sql,'添加签到奖励：' . $name));
            }
            Output::instance()->object([
                'code' => 0,
                'signRewardId' => $signId,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**签到奖励列表
     * @param string $name 名称搜索字段
     * @param string $startTime 更新时间筛选开始时间
     * @param string $endTime 更新时间筛选截止时间
     * @param string $tagId 标签筛选
     * @param int $start
     * @param int $limit
     */
    public function signRewardList($name = '', $startTime = '', $endTime = '', $tagId = '', $start = 0, $limit = 10)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $pointSchemeModel = M('module_point_scheme');
        $signInModel = M('sign_in_reward');
        $signTagModel = M('sign_reward_tag');
        $tagModel = M('sign_tag');
        Session::switchCustomer($customerId);

        /*根据传值组织查询条件*/
        if (!empty($tagId)) {
            $signRewardIds = $signTagModel->where(['tagId' => $tagId])->getField('signRewardId', true);
            $str_signRewardIds = implode(',', $signRewardIds);
            $where['id'] = ['in', $str_signRewardIds];
        }
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['updateTime'] = ['BETWEEN', [$start_time, $end_time]];
        }
        if (!empty($name)) $where['name'] = ['LIKE', '%' . $name . '%'];
        $where['deleted'] = 0;
        $where['cid'] = $customerId;

        $list = $signInModel->where($where)->order('updateTime desc')->limit($start, $limit)->select();
        /*插入标签信息*/
        foreach ($list as $key => $value) {
            $schemeTagWhere['signRewardId'] = $value['id'];
            $pointSchemeName = $pointSchemeModel->where(['id' => $value['pointSchemeId']])->getField('name');
            $tagIds = $signTagModel->where($schemeTagWhere)->getField('tagId', true);//获取标签id
            $tagConfigs = [];
            foreach ($tagIds as $tagId) {
                $tagName = $tagModel->where("id = $tagId")->getField('name');
                $tagConfig = ['id' => $tagId, 'name' => $tagName];
                array_push($tagConfigs, $tagConfig);
            }
            $list[$key]['tagConfigs'] = $tagConfigs;//插入标签信息
            $list[$key]['pointSchemeName'] = $pointSchemeName;
        }
        $total = $signInModel->where($where)->count();
        (empty($list)) ? $list=[] : '';
        Output::instance()->object([
            'code' => 0,
            'data' => $list,
            'total' => $total
        ]);
    }

    public function getSignRewardById($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signInModel = M('sign_in_reward');
        $signTagModel = M('sign_reward_tag');
        $tagModel = M('sign_tag');
        Session::switchCustomer($customerId);

        $result = $signInModel->where(['id' => $id, 'deleted' => 0])->find();
        $signTagWhere['signRewardId'] = $id;
        $tagIds = $signTagModel->where($signTagWhere)->getField('tagId', true);
        $tagConfigs = [];
        /*插入标签信息*/
        foreach ($tagIds as $tagId) {
            $tagName = $tagModel->where("id = $tagId")->getField('name');
            $tagConfig = ['id' => $tagId, 'name' => $tagName];
            array_push($tagConfigs, $tagConfig);
        }
        $result['tagConfigs'] = $tagConfigs;

        Output::instance()->object([
            'code' => 0,
            'data' => $result
        ]);
    }

    /**删除签到奖励
     * @param $id
     */
    public function deleteSignReward($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signInModel = M('sign_in_reward');
        Session::switchCustomer($customerId);

        $data = [
            'deleted' => 1,
            'deleteTime' => date('Y-m-d H:i:s', time())
        ];
        $res = $signInModel->where("id = $id")->save($data);

        if (is_numeric($res)) {
            $sql = $signInModel->getLastSql();
            $name = $res = $signInModel->where("id = $id")->getField('name');
            R('Log/add',array('signReward','','签到奖励',op_delete,$sql,'删除签到奖励：' . $name));
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**添加签到奖励标签
     * @param $name
     */
    public function addSignTag($name)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('sign_tag');
        Session::switchCustomer($customerId);

        $isHave = $tagModel->where(['name' => $name, 'cid' => $customerId])->find();
        if ($isHave) {
            Output::instance()->object([
                'code' => 1,
                'msg' => '此名称的标签已经存在'
            ]);
            return;
        }
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'createTime' => date('Y-m-d H:i:s', time())
        );

        $res = $tagModel->add($data);

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'tagId' => $res,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**删除签到奖励标签
     * @param $id
     */
    public function deleteSignTag($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('sign_tag');
        $signTagModel = M('sign_reward_tag');
        Session::switchCustomer($customerId);

        $tagModel->startTrans();
        $res = $tagModel->where("id = $id")->delete();
        $res2 = $signTagModel->where("tagId = $id")->delete();//删除此标签与积分方案的关联关系

        if (is_numeric($res) && is_numeric($res2)) {
            $tagModel->commit();
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            $tagModel->rollback();
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**
     * 获取签到奖励标签
     */
    public function getSignTag()
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('sign_tag');
        Session::switchCustomer($customerId);

        $where['cid'] = $customerId;

        $tag = $tagModel->where($where)->select();
        (empty($tag)) ? $tag=[] : '';
        Output::instance()->object($tag);

    }

    /**获取签到记录列表
     * @param $id
     * @param string $name
     * @param string $startTime
     * @param string $endTime
     * @param int $start
     * @param int $limit
     */
    public function signRecordList($id, $name = '', $startTime = '', $endTime = '', $start = 0, $limit = 10)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $recordModel = M('sign_record');
        Session::switchCustomer($customerId);

        if (!empty($name)) $where['u.fullName'] = ['like', '%' . $name . '%'];
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['r.time'] = ['BETWEEN', [$start_time, $end_time]];
        }
        $where['r.cid'] = $customerId;
        $where['r.signId'] = $id;

        $result = $recordModel->alias('r')
            ->join('wx_' . $customerId . '_user u on u.id = r.userId')
            ->where($where)
            ->field('r.*, u.fullName')
            ->limit($start, $limit)
            ->order('time desc')
            ->select();
        if (empty($result)) $result = [];

        $total = $recordModel->alias('r')
            ->join('wx_' . $customerId . '_user u on u.id = r.userId')
            ->where($where)
            ->order('time desc')
            ->count();

        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'total' => $total,
            'data' => $result
        ]);
    }

    public function getSignUrl($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $module = 'signIn';
        $method = 'index';
        $params = json_encode(['id' => $id]);

        $result = R('Purse/getPhoneUrl', [$module, $method, $params]);

        Output::instance()->object([
            'code' => 0,
            'url' => $result
        ]);
    }
}